<template>
  <!-- <a-form-item-rest> -->
  <a-popover
    v-model:open="open"
    :get-popup-container="bindParent ? (triggerNode) => triggerNode.parentNode : null"
    trigger="click"
    placement="bottomLeft"
    :align="{ offset: [0, 0] }"
  >
    <template #content>
      <a-table
        size="small"
        :loading="loading"
        :pagination="false"
        :style="{ width: tableWidth + 'px' }"
        :data-source="tableData"
        :columns="config.columns"
        :row-key="config.rowKey"
        :scroll="{ y: 250 }"
        class="select-table-style"
        :custom-row="(record) => ({ onClick: () => onSelect(record) })"
        :row-class-name="getRowClassName"
        @resize-column="(w, col) => (col.width = w)"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'mc'">
            <MedicineInfo :value="{ mc: record.mc, gg: record.gg, cj: record.cj }" :record="record" :type="type" />
          </template>
          <template v-if="column.dataIndex === 'equipmentName'">
            <MedicineInfo :value="{ mc: record.equipmentName, gg: record.specifications, cj: record.manufacturer }" />
          </template>
          <template v-if="column.dataIndex === 'applyPath' && type === '检验条码'"> {{ record.applyPath === 0 ? '门诊' : '住院' }}</template>
          <template v-if="column.dataIndex === 'applyDeptName' && type === '检验条码'"> {{ record.applyDeptName }}/{{ record?.lastBedCode }} </template>
          <template v-if="column.dataIndex === 'brName' && type === '检验条码'"> {{ record.brName }} {{ record?.brXb }} {{ record?.brAge }}</template>
        </template>
      </a-table>
    </template>
    <a-input
      ref="inputRef"
      v-model:value="inputValue"
      :placeholder="placeholder"
      :bordered="bordered"
      :class="className"
      :disabled="disabled"
      :size="large"
      :allow-clear="allowClear"
      @keydown="onKeyDown"
      @change="onSearch"
      @focus="onFocus"
      @blur="onBlur"
    >
      <template v-if="showSuffix" #suffix>
        <LoadingOutlined v-if="loading" :style="{ color: '#00000040', fontSize: '12px' }" />
      </template>
    </a-input>
  </a-popover>
  <!-- </a-form-item-rest> -->
</template>

<script setup>
/**
 * @name:在Table中选择项目
 */
import { ref, watch, nextTick } from 'vue'
import { Form, message } from 'ant-design-vue'
import { LoadingOutlined } from '@ant-design/icons-vue'
import { debounce } from 'lodash-es'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import useKeyboard from './useKeyboard'
import { getSelectTableConfig } from './config'

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  type: {
    desc: '配置文件类型',
    type: String,
    required: true,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  autoFocus: {
    type: Boolean,
    default: false
  },
  tableWidth: {
    type: Number,
    default: 620
  },
  showSuffix: {
    desc: 'loading图标',
    type: Boolean,
    default: false
  },
  defaultValue: {
    type: String,
    default: ''
  },
  defaultValueKey: {
    type: String,
    default: ''
  },
  bordered: {
    type: Boolean,
    default: true
  },
  multiple: {
    desc: '是否多选',
    type: Boolean,
    default: false
  },
  emptyClose: {
    desc: '没有数据时是否关闭弹窗',
    type: Boolean,
    default: false
  },
  autoMark: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  className: {
    type: String,
    default: ''
  },
  customInput: {
    desc: '自定义输入内容',
    type: Boolean,
    default: false
  },
  searchParams: {
    desc: '搜索条件',
    type: Object,
    default: () => ({})
  },
  unPage: {
    desc: '不分页',
    type: Boolean,
    default: false
  },
  rowDisabled: {
    type: Function,
    default: () => ''
  },
  selectFirst: {
    type: Boolean,
    default: false
  },
  selectOnlyOne: {
    type: Boolean,
    default: false
  },
  large: {
    type: String,
    default: ''
  },
  allowClear: {
    type: Boolean,
    default: false
  },
  bindParent: {
    desc: '绑定到父元素',
    type: Boolean,
    default: false
  }
})
const open = ref(false)
const loading = ref(false)
const isSelected = ref(false)
const inputValue = ref()
const inputRef = ref()
const config = ref({})
const tableData = ref([])
const emit = defineEmits(['select', 'close', 'update:value', 'custom', 'clear', 'delete', 'inputChange', 'enter', 'scanCode'])
const formItemContext = Form.useInjectFormItemContext()

const onSelect = (row) => {
  emit('select', row)
  isSelected.value = true
  open.value = props.multiple ? true : false
  formItemContext.onFieldChange()
}
const getRowClassName = (row, index) => {
  if (props.rowDisabled(row)) {
    row.disabled = true
    return 'bg-red-50 pointer-events-none text-disabled'
  } else {
    return keyboardRowClassName(index)
  }
}
//键盘操作
const { keyboardRowClassName, onKeyDown } = useKeyboard(tableData, onSelect, emit, inputValue, props)

const onFocus = () => {
  queryData()
  props.autoMark && setTimeout(() => inputRef.value?.setSelectionRange(0, inputValue.value?.length), 100)
  if (props.multiple && inputValue.value) {
    inputValue.value += '，'
  }
}
const onBlur = () => {
  if (inputValue.value?.substr(-1) === '，' || inputValue.value?.substr(-1) === ',') {
    inputValue.value = inputValue.value.substring(0, inputValue.value.length - 1)
  }
  inputValue.value = inputValue.value?.replaceAll(',', '，')
  // if (!inputValue.value) emit('clear')
  // emit('blur', inputValue.value)
}

const onSearch = debounce((e) => {
  const value = e.target?.value.trim()
  emit('inputChange', value)
  if (props.multiple) {
    const index = value.lastIndexOf('，') || value.lastIndexOf(',')
    const searchValue = value.substring(index + 1, value.length)
    queryData(searchValue)
  } else {
    queryData(value, true)
  }
}, 500)
let fetchFlag = 1
//获取数据
const queryData = async (value = '', isSearch = false) => {
  const { url, params = {}, searchKey } = config.value
  loading.value = true
  isSelected.value = false
  tableData.value = []
  if (searchKey) {
    params[searchKey] = value
  }
  const checkFlag = ++fetchFlag
  params.pageSize = props.unPage ? '' : '30'
  if (getSystemConfig('IS_EMP_COMPONENT_PAGEING') === '0' && config.value.desc === '选择员工') {
    params.pageSize = ''
  }
  const { code, data } = await post(url, { ...params, ...props.searchParams })
  loading.value = false
  if (checkFlag !== fetchFlag) return console.info('[Warn] 重复请求已忽略', `【${url}】`)
  if (code !== 0) return message.error('获取数据失败')
  tableData.value = data || []
  if (props.selectFirst && tableData.value.length) {
    emit('select', { ...tableData.value[0], autoSelected: true })
  }
  if (props.selectOnlyOne && tableData.value.length === 1) {
    emit('select', { ...tableData.value[0], autoSelected: true })
  }
  if (data.length > 0 && !open.value && isSearch) {
    open.value = true
  }
  if (props.defaultValue && props.defaultValueKey && tableData.value.length > 0) {
    const defaultRow = tableData.value.find((item) => item[props.defaultValueKey] === props.defaultValue)
    defaultRow && emit('select', { ...defaultRow, autoSelected: true })
  }

  if (props.emptyClose && !tableData.value.length) {
    setTimeout(() => {
      open.value = false
    }, 100)
  }
}

watch(
  () => props.selectFirst,
  (val) => {
    val && queryData()
  }
)
watch(
  () => props.selectOnlyOne,
  (val) => {
    val && queryData()
  }
)
watch(open, (val) => {
  if (!val) {
    emit('close')
    if (!isSelected.value) {
      props.customInput ? emit('custom') : (inputValue.value = props.value)
    }
  }
})
watch(inputValue, (val, oldVal) => {
  if (!val) {
    emit('clear', val) //清空
    if (props.allowClear) {
      oldVal && emit('select', {})
    }
    emit('update:value', '')
    // emit('select', {})
    // open.value = !!oldVal
  }
  if (props.multiple || props.customInput) {
    emit('update:value', val)
  }
})

watch(
  () => props.autoFocus,
  (val) => {
    nextTick(() => {
      if (val && inputRef.value && !props.disabled) {
        inputRef.value.focus()
        open.value = true
      }
    })
  },
  { immediate: true }
)

// //获取表头
// const getColumns = async () => {
//   const { code, data } = await post('/common/util/getTableMappingCloumnList', { id: '000835' })
//   if (code === 0 && data.length > 0) {
//     // 排除excludeColumns列和隐藏列
//     config.value.columns = data.filter((item) => {
//       item.width = item.width || 100
//       return !item.isHide
//     })
//   } else {
//     message.error(`获取表头【${props.columnCode}】失败`)
//   }
// }
watch(
  () => props.type,
  (val) => {
    val && (config.value = getSelectTableConfig(val))
    // getColumns()
    // props.selectFirst && queryData()
    props.selectOnlyOne && queryData()
    props.defaultValue && queryData()
  },
  { immediate: true }
)
watch(
  () => props.value,
  (val) => {
    inputValue.value = val
    if (!val && props.selectFirst && config.value.url) {
      queryData()
    }
    if (!val && props.defaultValue && config.value.url) {
      queryData()
    }
  },
  {
    immediate: true
  }
)
</script>
<style lang="less" scoped>
:deep(.ant-input-suffix) {
  z-index: 0;
}
:deep(.ant-table) {
  border: 1px solid var(--border-color);
  .ant-table-tbody {
    .ant-table-row {
      cursor: pointer;
    }
    .table-row-selected {
      background-color: var(--secondary-color);
    }
    td {
      padding: 4px 8px !important;
    }
  }
  .ant-table-measure-row {
    visibility: collapse;
  }
}
</style>
